#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# Author: Binux<i@binux.me>
#         http://binux.me
# Created on 2014-10-19 15:37:46


import logging
import time
from six.moves import queue as Queue
logger = logging.getLogger("group")


class AggregationWorker(object):

    """
    do with result
    override this if needed.
    """

    def __init__(self, groupdb, inqueue):
        self.groupdb = groupdb
        self.inqueue = inqueue
        self._quit = False

    def on_result(self, task, result):
        '''Called every result'''
        if not result:
            return
        time_format = '%Y-%m-%d'
        now = time.strftime(time_format, time.localtime())
        logger.info("task: ", task)
        if isinstance(result.get('keyword', {}), str):
            self.groupdb.insert_group(
                group_keyword=result.get('keyword', {}),
                resultid='%s:%s' % (task['project'], task['taskid']),
                title=result.get('title', {}),
                url=task['url'],
                project=task['project'],
                date=result.get('date', now))
        if isinstance(result.get('keyword', {}), list):
            for keyword in result.get('keyword', {}):
                self.groupdb.insert_group(
                    group_keyword=keyword,
                    resultid='%s:%s' % (task['project'], task['taskid']),
                    title=result.get('title', {}),
                    url=task['url'],
                    project=task['project'],
                    date=result.get('date', now))
        return True

    def quit(self):
        self._quit = True

    def run(self):
        '''Run loop'''
        logger.info("aggregation_worker starting...")

        while not self._quit:
            try:
                task, result = self.inqueue.get(timeout=1)
                if not result.get('keyword', {}):
                    continue
                else:
                    self.on_result(task, result)
            except Queue.Empty as e:
                continue
            except KeyboardInterrupt:
                break
            except AssertionError as e:
                logger.error(e)
                continue
            except Exception as e:
                logger.exception(e)
                continue

        logger.info("aggregation_worker exiting...")
